import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';

var workerPort : ThreadWorkerGlobalScope = worker.workerPort;

let TAG = "TEST_WORKER_FIELD";

/**
* Defines the event handler to be called when the worker thread receives a message sent by the host thread.
* The event handler is executed in the worker thread.
*
* @param data message data
*/
workerPort.onmessage = function(data) {
  console.log(`${TAG}, workerPort.onMessage: ` + JSON.stringify(data));

  // 模拟一个耗时任务
  setTimeout(() => {
    // 耗时结束后，向宿主线程发送消息
    workerPort.postMessage("Hello, Worker, I'm sub thread");
  }, 3000);
}

/**
* Defines the event handler to be called when the worker receives a message that cannot be deserialized.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
workerPort.onmessageerror = function(e : MessageEvents) {
  console.log(`${TAG}, workerPort.onmessageerror: ` + JSON.stringify(e));
}

/**
* Defines the event handler to be called when an exception occurs during worker execution.
* The event handler is executed in the worker thread.
*
* @param e error message
*/
workerPort.onerror = function(e : ErrorEvent) {
  console.log(`${TAG}, workerPort.onerror: ` + JSON.stringify(e));
}